﻿#region Copyright (c) 2013-04, Olaf Kober <amarok.projects@gmail.com>
//================================================================================
//	Permission is hereby granted, free of charge, to any person obtaining a copy
//	of this software and associated documentation files (the "Software"), to deal
//	in the Software without restriction, including without limitation the rights
//	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//	copies of the Software, and to permit persons to whom the Software is
//	furnished to do so, subject to the following conditions:
//
//	The above copyright notice and this permission notice shall be included in
//	all copies or substantial portions of the Software.
//
//	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//	THE SOFTWARE.
//================================================================================
#endregion

using System;
using System.Diagnostics;
using System.Globalization;
using System.Threading.Tasks;


namespace Amarok
{
	/// <summary>
	/// This type provides extension methods for <see cref="System.Threading.Tasks.Task"/>.
	/// </summary>
	public static class TaskExtensions
	{
		#region ++ Public Interface (IgnoreExceptions) ++

		/// <summary>
		/// This method registers a continuation on the task that swallows otherwise un-handled exceptions. 
		/// The exception is logged and then ignored.
		/// </summary>
		/// 
		/// <param name="task">
		/// The task on which to register the continuation.</param>
		/// 
		/// <returns>
		/// A reference to the supplied task, or null if a null reference was supplied.</returns>
		public static Task IgnoreExceptions(this Task task)
		{
			if (task == null)
				return null;

			task.ContinueWith(t =>
				{
					var exception = t.Exception;

					#region (tracing)
					{
						Trace.WriteLine(String.Format(CultureInfo.InvariantCulture,
							"*** ERROR: UNHANDLED TASK EXCEPTION:" +
							"\r\n  Task.Id: {0}" +
							"\r\n{1}",
							task.Id,
							Helper.FormatException(exception, CultureInfo.InvariantCulture)
						));
					}
					#endregion
				},
				TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously);

			return task;
		}

		/// <summary>
		/// This method registers a continuation on the task that swallows otherwise un-handled exceptions. The
		/// exception is logged and then ignored.
		/// </summary>
		/// 
		/// <param name="task">
		/// The task on which to register the continuation.</param>
		/// 
		/// <returns>
		/// A reference to the supplied task, or null if a null reference was supplied.</returns>
		public static Task<TResult> IgnoreExceptions<TResult>(this Task<TResult> task)
		{
			if (task == null)
				return null;

			task.ContinueWith(c =>
				{
					var exception = c.Exception;

					#region (tracing)
					{
						Trace.WriteLine(String.Format(CultureInfo.InvariantCulture,
							"*** ERROR: UNHANDLED TASK EXCEPTION:" +
							"\r\n  Task.Id={0}" +
							"\r\n{1}",
							task.Id,
							Helper.FormatException(exception, CultureInfo.InvariantCulture)
						));
					}
					#endregion
				},
				TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously);

			return task;
		}

		#endregion

		#region ++ Public Interface (WaitQuietly) ++

		/// <summary>
		/// This method blocks the current thread until the supplied task completes much like Task.Wait(), but in
		/// contrast to Task.Wait() this method does not throw an exception in case that the task was canceled or 
		/// completed in a faulted state.
		/// </summary>
		/// 
		/// <param name="task">
		/// The task for which completion to wait.</param>
		/// 
		/// <exception cref="ArgumentNullException">
		/// A null reference was passed to a method that did not accept it as a valid argument.</exception>
		public static void WaitQuietly(this Task task)
		{
			Verify.NotNull(task, "task");

			var waitTask = task.ContinueWith(t =>
				{
					// nothing to do
				},
				TaskScheduler.Default);

			waitTask.Wait();
		}

		/// <summary>
		/// This method blocks the current thread until the supplied task completes much like Task.Wait(), but in
		/// contrast to Task.Wait() this method does not throw an exception in case that the task was canceled or 
		/// completed in a faulted state.
		/// </summary>
		/// 
		/// <param name="task">
		/// The task for which completion to wait.</param>
		/// <param name="millisecondsTimeout">
		/// The number of milliseconds to wait, or System.Threading.Timeout.Infinite (-1) to wait indefinitely.</param>
		/// 
		/// <exception cref="ArgumentNullException">
		/// A null reference was passed to a method that did not accept it as a valid argument.</exception>
		/// <exception cref="ArgumentOutOfRangeException">
		/// A value was passed to a method that did not accept it as a valid argument, because the value 
		/// must be positive (equal to or greater than zero).</exception>
		public static Boolean WaitQuietly(this Task task, Int32 millisecondsTimeout)
		{
			Verify.NotNull(task, "task");
			Verify.NotNegative(millisecondsTimeout, "millisecondsTimeout");

			var waitTask = task.ContinueWith(t =>
				{
					// nothing to do
				},
				TaskScheduler.Default);

			return waitTask.Wait(millisecondsTimeout);
		}

		/// <summary>
		/// This method blocks the current thread until the supplied task completes much like Task.Wait(), but in
		/// contrast to Task.Wait() this method does not throw an exception in case that the task was canceled or 
		/// completed in a faulted state.
		/// </summary>
		/// 
		/// <param name="task">
		/// The task for which completion to wait.</param>
		/// <param name="timeout">
		/// A TimeSpan that represents the number of milliseconds to wait, or a TimeSpan that represents -1 
		/// milliseconds to wait indefinitely.</param>
		/// 
		/// <exception cref="ArgumentNullException">
		/// A null reference was passed to a method that did not accept it as a valid argument.</exception>
		/// <exception cref="ArgumentOutOfRangeException">
		/// A value was passed to a method that did not accept it as a valid argument, because the value 
		/// must be positive (equal to or greater than zero).</exception>
		public static Boolean WaitQuietly(this Task task, TimeSpan timeout)
		{
			return TaskExtensions.WaitQuietly(
				task,
				(Int32)timeout.TotalMilliseconds);
		}

		#endregion

	}
}
